import { AjaxService, Req, Res } from "./ajax.service"
import { Injectable } from '@angular/core'

import { Plan } from "./plan"

@Injectable()
export class PlanService {
  private bh = AjaxService.APIROOT + '/plans';

  update(plan: Plan): Promise<Res> {
    var argv = { plan: plan, token: localStorage.getItem("token") }
    if (plan.id)
      return AjaxService.request(new Req(`${this.bh}/${plan.id}.json`, "PUT", argv))
    else
      return AjaxService.request(new Req(`${this.bh}.json`, "POST", argv))
  }

  
  getList(): Promise<Array<Plan>> {
    var argv = new Array();
    var token = localStorage.getItem("token")
    if (token)
      argv["token"] = token
    console.log(argv)
    var plans: Array<Plan> = [ ]
    return new Promise<Array<Plan>>(resolve => {
        AjaxService.request(new Req(`${this.bh}.json`, "GET", argv))
          .then(res => {
            if (!res.error)
              plans = res.data
            resolve()
          }).catch((err: any) => { console.log("get projects error", err) })
      }).then(() => plans)
  }

  get(id: string): Promise<Plan> {
    var plan: Plan
    var argv = {token: localStorage.getItem("token") }
    return new Promise<Plan>(resolve => {
      AjaxService.request(new Req(`${this.bh}/${id}.json`, "GET", argv))
          .then(res => {
            if (!res.error)
              plan = res.data
            resolve()
          }).catch((err: any) => { console.log("get task error", err) })
    }).then(() => plan)
  }
}
